package cn.lazyturtle.bugpush.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
public class HttpUtils {

    /**
     * httpGet 请求
     * @param url 请求地址
     * @param params    参数
     * @param charset   编码
     */
    public static String doGet(String url, Map<String, String> params, String charset) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        List<NameValuePair> nvps = new ArrayList<>();
        if (!CollectionUtils.isEmpty(params)) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpGet.setURI(URI.create(url + "?" + URLEncodedUtils.format(nvps, charset)));
        }
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            return getEntity(httpResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * httpPost 请求 JSON
     * @param url 请求地址
     * @param params    参数
     */
    public static String doPostByJson(String url, Map<String, Object> params) {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
            .setSocketTimeout(5000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        String entity = JSON.toJSONString(params);
        httpPost.setEntity(new StringEntity(entity, StandardCharsets.UTF_8));
        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            log.info("返回状态:" + httpResponse.getStatusLine());
            return getEntity(httpResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    private static String getEntity(HttpResponse httpResponse) throws IOException {
        if (httpResponse != null) {
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity responseEntity = httpResponse.getEntity();
                if (responseEntity != null) {
                    return EntityUtils.toString(responseEntity);
                }
            } else {
                return "Error Response " + httpResponse.getStatusLine().toString();
            }
        }
        return "";
    }

}

